<template>
  <div id="json">
    <p>降序</p>
    <ul class="list">
      <li v-for="elem in listDesc" :key="elem.key">{{elem.rate}}、</li>
    </ul>
    <br>
    <p>升序</p>
    <ul class="list">
      <li v-for="elem in listAsc" :key="elem.key">{{elem.rate}}、</li>
    </ul>
  </div>
</template>
<script>
import Tool from './json/tool.js'
const output = [
  {
    name: 'Tom',
    linesOfCode: 100,
    rate: '65%'
  }, {
    name: 'Jerry',
    linesOfCode: 200,
    rate: '10%'
  }, {
    name: 'Defore',
    linesOfCode: 50,
    rate: '15%'
  }, {
    name: 'Mibo',
    linesOfCode: 6,
    rate: '65%'
  }
]
export default {
  name: "json",
  data: () => ({
    listDesc: [],
    listAsc: []
  }),
  methods: {
    init () {
      let total = 0
      for (let i = 0, len = output.length; i < len; i++) {
        total += output[i].linesOfCode
      }
      console.log(total)
    },
    init2 () {
      const total = output
        .map((item) => item.linesOfCode) // 返回一个新数组，[linesOfCode, ... linesOfCode]
        .reduce((acc, linesOfCode) => acc + linesOfCode, 0)
      console.log(total)

      // reduce 方法参数
      /*
      array.reduce(callbackfn,[initialValue])

      function callbackfn(preValue,curValue,index,array){}
      preValue: 上一次调用回调返回的值，或者是提供的初始值（initialValue）
      curValue: 数组中当前被处理的数组项
      index: 当前数组项在数组中的索引值
      array: 调用 reduce()方法的数组
      */
    },
    sort () {
      this.listDesc = Tool.sortByKey(output, "rate");
      this.listAsc = Tool.sortByKey(output, "rate", true);
    }
  },
  mounted () {
    this.init()
    this.init2()
    this.sort()
  }
}
</script>
<style lang="scss" scoped>
.list {
  display: flex;
}
</style>
